using UnityEngine;
using System.Collections;

/**
 * Script of game end behaviour description.
 * The purpose of this class is to end the game.
 * @author Benjamin Bruneau
 */
public class EndScript : MonoBehaviour {
	
	private const string REPLAY_MODE_NAME = "ReplayMode"; // Replay Mode GameObject's name
	private const string STAGE_FINAL = "StageFinal"; // Replay Mode GameObject's name
	private const string BALL_NAME = "Ball"; // Main GameObject's name
	
	private GameObject _replayMode; // Replay Mode GameObject
	
	private bool _isGameOver = false; // Is game over
	private bool _isEndLaunched = false; // is end animation launched
	
	public GameObject _endSound; // End Sound GameObject
	public GameObject _gameOverSound; // End Sound GameObject
	public GameObject _dataContainer; // Data container GameObject
	public GameObject _ball; // Ball GameObject
	public GameObject _light; // Light to animate
	public GameObject _lightTwo; // Light to animate
	public GameObject _lightThree; // Light to animate
	public GameObject _lightFour; // Light to animate
	public GameObject _endBackground; // Ball GameObject
	
	public string _forward; //Application next scene
	
	/**
	 * Called on initialization.
	 * @return void
	 */
	void Start () 
	{
		
		//Initialized because this object moves through scenes
		_replayMode = GameObject.Find (REPLAY_MODE_NAME);
		
	}
	
	/**
	 * Called once per frame.
	 * @return void
	 */
	void Update () 
	{
		
		if (_isGameOver && _isEndLaunched) 
		{
			if(!_endBackground.GetComponent<Animation>().isPlaying)
			{
				_endBackground.GetComponent<MeshRenderer>().enabled = true;
			}
			
			if(!_light.GetComponent<Animation>().isPlaying)
			{
				// Destroys replay mode
				if (_replayMode != null)
				{
					Destroy(_replayMode);
				}

				//Next Scene
				Application.LoadLevel(_forward);
			}
		}
		
		// Update timer
		if (_isGameOver && !_isEndLaunched) 
		{
		 //launch anim
			_endBackground.GetComponent<Animation>().Play();
			_light.GetComponent<Animation>().Play();
			_lightTwo.GetComponent<Animation>().Play();
			_lightThree.GetComponent<Animation>().Play();
			_lightFour.GetComponent<Animation>().Play();		
			_isEndLaunched = true;
		}
		
		
		
	}
	
	/*
	 * Called on collision.
	 * @param Collision
	 * @return void
	 */
	void OnCollisionEnter(Collision pCollision)
	{
		//If collide with the ball
		if (pCollision.gameObject.name.Equals(BALL_NAME))
		{
			//Win
			if (this.gameObject.name.Equals(STAGE_FINAL)){
				_dataContainer.GetComponent<TimeScript>().gameWon();
				_endSound.GetComponent<AudioSource>().Play();
			} else {
				_gameOverSound.GetComponent<AudioSource>().Play();
			}
			_ball.GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezeAll;
			//Stop time
			_dataContainer.GetComponent<TimeScript>()._isPlaying = false;
			_isGameOver = true;
			
		}	
	}
}
